package com.uduew.sjd.utils

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context

class ClipboardHelper(private val context: Context) {
    private val clipboardManager =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

    /**
     * 将文本复制到剪贴板
     *
     * @param text 要复制的文本
     */
    fun copyText(text: String?) {
        val clipData = ClipData.newPlainText("text", text)
        clipboardManager.setPrimaryClip(clipData)
    }

    val copiedText: String?
        /**
         * 从剪贴板获取文本
         *
         * @return 剪贴板中的文本
         */
        get() {
            if (clipboardManager.hasPrimaryClip()) {
                val clipData = clipboardManager.primaryClip
                if (clipData != null && clipData.itemCount > 0) {
                    val text = clipData.getItemAt(0).text
                    return text.toString()
                }
            }
            return null
        }

}